//
// Created by lanlu on 2025/8/7.
//

#include <stack>
#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x) : val(x), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right)
    {
    }
};

class Solution {
public:
    int sumEvenGrandparent(TreeNode* root) {
        if (root == nullptr) return 0;

        stack<TreeNode*> s;
        s.push(root);
        int sum = 0;

        while (!s.empty())
        {
            TreeNode * node = s.top();
            s.pop();

            if (node -> val % 2 == 0)
            {
                if (node -> left != nullptr)
                {
                    if (node -> left -> left != nullptr)
                    {
                        sum += node -> left -> left -> val;
                    }
                    if (node -> left -> right != nullptr)
                    {
                        sum += node -> left -> right -> val;
                    }
                }

                if (node -> right != nullptr)
                {
                    if (node -> right -> left != nullptr)
                    {
                        sum += node -> right -> left -> val;
                    }
                    if (node -> right -> right != nullptr)
                    {
                        sum += node -> right -> right -> val;
                    }
                }
            }

            if (node -> right != nullptr)
            {
                s.push(node -> right);
            }

            if (node -> left != nullptr)
            {
                s.push(node -> left);
            }
        }

        return sum;
    }
};